import { defineStore } from 'pinia'

// src/stores/useOrderStore.ts
// 定义订单商品接口
export interface OrderItem {
    name: string;
    quantity: number;
    price: number;
}

// 定义订单接口
export interface Order {
    shopName: string;
    status: string;
    totalPrice: number;
    items: OrderItem[];
    id: string; // 唯一标识符
}

interface Order {
    id: string;
    shopName: string;
    status: string; // e.g., '待支付', '已完成'
    items: Array<{ name: string; quantity: number }>;
    totalPrice: number;
    paymentMethod?: 'alipay' | 'wechat'; // New property
}

function addOrder(order: Order) {
    orders.value.push(order);
    localStorage.setItem('orders', JSON.stringify(orders.value)); // <-- 确保这里保存了完整的 order 对象
}

// 创建 store
export const useOrderStore = defineStore('order', {
    state: () => ({
        orders: [] as Order[],
    }),
    getters: {
        getOrders(): Order[] {
            return this.orders;
        },
    },
    actions: {
        addOrder(newOrder: Omit<Order, 'id'>) {
            const id = `order_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            this.orders.push({
                ...newOrder,
                id,
            });
        },
        loadOrdersFromLocalStorage() {
            const savedOrders = localStorage.getItem('user-orders');
            if (savedOrders) {
                this.orders = JSON.parse(savedOrders);
            }
        },
        saveOrdersToLocalStorage() {
            localStorage.setItem('user-orders', JSON.stringify(this.orders));
        },
    },
});

// 🔧 用户状态接口定义
interface UserState {
    name: string
    token: string | null
}

// 📦 用户 Store
export const useUserStore = defineStore('user', {
    state: (): UserState => ({
        name: '',
        token: localStorage.getItem('user-token') || null,
    }),

    getters: {
        // ✅ 判断是否已登录
        isAuthenticated(): boolean {
            return this.token !== null
        },

        // ✅ 获取当前用户名（可扩展为从后端获取）
        currentUserName(): string {
            return this.name || '游客'
        },
    },

    actions: {
        // 📤 登录操作：保存 token 并设置本地存储
        login(token: string) {
            this.token = token
            localStorage.setItem('user-token', token)
        },

        // 🔐 登出操作：清除 token 和本地存储
        logout() {
            this.token = null
            localStorage.removeItem('user-token')
        },

        // 👤 设置用户名（可用于从 API 获取用户信息后调用）
        setUserName(name: string) {
            this.name = name
        }
    },
})